package com.burst.reptile.modular.system.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.burst.reptile.common.constant.Constants;
import com.burst.reptile.common.constant.UserConstants;
import com.burst.reptile.common.utils.SecurityUtils;
import com.burst.reptile.common.utils.ToolUtil;
import com.burst.reptile.common.utils.poi.ExcelUtil;
import com.burst.reptile.framework.aspectj.lang.annotation.Log;
import com.burst.reptile.framework.aspectj.lang.enums.BusinessType;
import com.burst.reptile.framework.web.controller.BaseController;
import com.burst.reptile.framework.web.result.LayuiResult;
import com.burst.reptile.framework.web.result.Result;
import com.burst.reptile.modular.system.entity.SysRole;
import com.burst.reptile.modular.system.entity.SysUser;
import com.burst.reptile.modular.system.service.ISysPostService;
import com.burst.reptile.modular.system.service.ISysRoleService;
import com.burst.reptile.modular.system.service.ISysUserService;

import cn.hutool.core.util.StrUtil;
import lombok.RequiredArgsConstructor;

/**
 * <p>
 * 用户信息表 前端控制器
 * </p>
 * 
 * @author wujin
 * @since 2020-05-21
 */
@RestController
@RequestMapping("/system/user")
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class SysUserController extends BaseController {

	private final ISysUserService userService;

	private final ISysRoleService roleService;

	private final ISysPostService postService;
	
	/**
	 * 获取用户列表
	 */
	@PreAuthorize("@ss.hasPermi('system:user:list')")
	@GetMapping("/list")
	public LayuiResult<Object> list(SysUser user) {
		Page<SysUser> page = startPage();
		Page<SysUser> list = userService.selectUserList(page, user);
		return LayuiResult.success(list.getTotal(), list.getRecords());
	}

	/**
	 * 新增用户
	 */
	@PreAuthorize("@ss.hasPermi('system:user:add')")
	@Log(title = "用户管理", businessType = BusinessType.INSERT)
	@PostMapping("/add")
	public Result<Object> add(@Validated @RequestBody SysUser user) {
		if (UserConstants.NOT_UNIQUE.equals(userService.checkUserNameUnique(user.getUserName()))) {
			return Result.error("新增用户'" + user.getUserName() + "'失败，登录账号已存在");
		} else if (UserConstants.NOT_UNIQUE.equals(userService.checkPhoneUnique(user))) {
			return Result.error("新增用户'" + user.getUserName() + "'失败，手机号码已存在");
		} else if (UserConstants.NOT_UNIQUE.equals(userService.checkEmailUnique(user))) {
			return Result.error("新增用户'" + user.getUserName() + "'失败，邮箱账号已存在");
		}
		user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
		String sex = user.getSex();
		if(ToolUtil.isNotEmpty(sex)) {
			if(StrUtil.equals(sex, "0")) {
				user.setAvatar(Constants.BOY_AVATAR);
			}else if(StrUtil.equals(sex, "1")) {
				user.setAvatar(Constants.GIRL_AVATAR);
			}
		}
		return Result.success(userService.insertUser(user));
	}

	/**
	 * 修改用户
	 */
	@PreAuthorize("@ss.hasPermi('system:user:edit')")
	@Log(title = "用户管理", businessType = BusinessType.UPDATE)
	@PutMapping("/edit")
	public Result<Object> edit(@Validated @RequestBody SysUser user) {
		userService.checkUserAllowed(user);
		if (UserConstants.NOT_UNIQUE.equals(userService.checkPhoneUnique(user))) {
			return Result.error("修改用户'" + user.getUserName() + "'失败，手机号码已存在");
		} else if (UserConstants.NOT_UNIQUE.equals(userService.checkEmailUnique(user))) {
			return Result.error("修改用户'" + user.getUserName() + "'失败，邮箱账号已存在");
		}
		user.setUpdateUser(SecurityUtils.getUsername());
		return Result.success(userService.updateUser(user));
	}

	/**
	 * 删除用户
	 */
	@PreAuthorize("@ss.hasPermi('system:user:remove')")
	@Log(title = "用户管理", businessType = BusinessType.DELETE)
	@DeleteMapping("/remove/{userIds}")
	public Result<Object> remove(@PathVariable Long[] userIds) {
		return Result.success(userService.deleteUserByIds(userIds));
	}

	/**
	 * 重置密码
	 */
	@PreAuthorize("@ss.hasPermi('system:user:edit')")
	@Log(title = "用户管理", businessType = BusinessType.UPDATE)
	@PutMapping("/resetPwd")
	public Result<Object> resetPwd(@RequestBody SysUser user) {
		userService.checkUserAllowed(user);
		SysUser sysUser = new SysUser();
		sysUser.setUserId(user.getUserId());
		sysUser.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
		sysUser.setUpdateUser(SecurityUtils.getUsername());
		return Result.success(userService.resetPwd(sysUser));
	}

	/**
	 * 根据用户编号获取详细信息
	 * 
	 * @param userId
	 * @return
	 */
	@PreAuthorize("@ss.hasPermi('system:user:query')")
	@GetMapping(value = { "/", "/{userId}" })
	public Result<Object> getInfo(@PathVariable(value = "userId", required = false) Long userId) {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("roles", roleService.selectRoleAll(new SysRole()));
		map.put("posts", postService.selectPostAll());
		if (ToolUtil.isNotEmpty(userId)) {
			map.put("user", userService.getById(userId));
			map.put("postIds", postService.selectPostListByUserId(userId));
			map.put("roleIds", roleService.selectRoleListByUserId(userId));
		}
		return Result.success(map);
	}

	/**
	 * 状态修改
	 */
	@PreAuthorize("@ss.hasPermi('system:user:edit')")
	@Log(title = "用户管理", businessType = BusinessType.UPDATE)
	@PutMapping("/changeStatus")
	public Result<Object> changeStatus(@RequestBody SysUser user) {
		userService.checkUserAllowed(user);
		return Result.success(userService.updateUserStatus(user));
	}

	/**
	 * 导出用户
	 * @param user
	 * @return
	 */
	@Log(title = "用户管理", businessType = BusinessType.EXPORT)
	@PreAuthorize("@ss.hasPermi('system:user:export')")
	@GetMapping("/export")
	public Result<Object> export(SysUser user) {
		List<SysUser> list = userService.selectUserList(user);
		ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
		return util.exportExcel(list, "用户数据");
	}
	
	/**
	 * 导入用户
	 * @param file 文件域
	 * @param updateSupport 存在是否更新
	 * @return
	 * @throws Exception
	 */
	@Log(title = "用户管理", businessType = BusinessType.IMPORT)
    @PreAuthorize("@ss.hasPermi('system:user:import')")
    @PostMapping("/importData")
    public Result<Object> importData(MultipartFile file, boolean updateSupport) throws Exception {
        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
        List<SysUser> userList = util.importExcel(file.getInputStream());
        String message = userService.importUser(userList, updateSupport);
        return Result.success(message);
    }

}
